$(function() {
	var	bucketSelectDiv = $('#bucketDiv .btn-group'),
		bucketEditBtn = $('#bucketDiv button:first'),

		resourceListPanel = $('#resourceListPanel .panel-body'),
		resourceListDiv = $('#resourceListPanel table tbody'),
		resourceSelectInput = $('table thead input'),

		uploadBtn = $('#uploadBtn'),
		searchBtn = $('#searchBtn'),
		searchInput = $('#searchInput'),

		paginationDiv = $('#pagination');

	var fileSizeExt = ['Bytes', 'KB', 'MB', 'GB'];

	var dataStorage = {
		buckets: {
			current: undefined,
			all: []
		},
		page: {
			totalPages: 0,
			currentPage: 0,
			pagination: undefined
		},
		searchKey: undefined,
	}

	resourceListPanel.height($(window).height() - 250);
	$(window).resize(function() {
	    resourceListPanel.height(Math.max($(this).height() - 250, 300));
	});

	disableView(true);

	$.get(URLS['STORAGE_BUCKET_LIST_URL'], function(list) {
	    $.each(list, function(i, bucket) {
	        bucketSelectDiv.find('ul').append('<li data-sid="' + bucket.sid + '"><a href="#">' + bucket.name + bucket.desc + '</a></li>');
	        dataStorage.buckets.all.push(bucket);
	    });
	    bucketSelectDiv.find('a').slice(1).on('click', function(e) {
	    	e.preventDefault();
	    	onBucketSelectFn($(this));
	    });
	});

	bucketSelectDiv.find('a:first').on('click', function(e) {
	    e.preventDefault();
	    var bucketAddModal = $.dfaceModal({
	        title: '添加空间',
	        content: constructBucketForm({}),
	        isForm: true,
	        btns: ['取消', '确定']
	    }).show();
	    bucketAddModal.find('#btnOk').on('click', function() {
	        var postParam = {
	            name: bucketAddModal.find('form input:first').val(),
	            url: bucketAddModal.find('form input:eq(1)').val(),
	            desc: bucketAddModal.find('form input:last').val()
	        };
	        $.post(URLS['STORAGE_BUCKET_ACTION_ADD_URL'], postParam, function(result) {
	            if (result.succeeded) {
	                var bucket = result.obj,
	                	newBucketDiv = $('<li data-sid="' + bucket.sid + '"><a href="#">' + bucket.name + '</a></li>');
	                newBucketDiv.find('a').on('click', function(e) {
	                	e.preventDefault();
	                	onBucketSelectFn($(this));
	                });
	                dataStorage.buckets.all.push(bucket);
	                bucketSelectDiv.find('ul').append(newBucketDiv);
	                bucketAddModal.modal('hide');
	            } else {
	                bucketAddModal.find('form').before($.dfaceAlert('danger', '<strong>Error: </strong>' + result.message));
	            }
	        });
	    });
	});

	bucketEditBtn.on('click', function(e) {
	    var currentBucket = dataStorage.buckets.current;
	    var bucketEditModal = $.dfaceModal({
	        title: '更新空间',
	        content: constructBucketForm(currentBucket),
	        isForm: true,
	        btns: ['取消', '确定']
	    }).show();
	    bucketEditModal.find('#btnOk').on('click', function() {
	        var postParam = {
	            name: bucketEditModal.find('form input:first').val(),
	            url: bucketEditModal.find('form input:last').val()
	        };
	        $.post(URLS['STORAGE_BUCKET_BY_ID_URL'] + currentBucket.sid, postParam, function(result) {
	            if (result.succeeded) {
	                currentBucket.name = postParam.name;
	                currentBucket.url = postParam.url;
	                bucketSelectDiv.find('button').html(postParam.name + ' <span class="caret">');
	                bucketSelectDiv.find('li')
	                			   .filter('[data-sid="' + dataStorage.buckets.current.sid + '"]')
	                			   .find('a')
				                   .attr('href', postParam.url)
				                   .text(postParam.name);
				    bucketEditModal.modal('hide');
	            } else {
	            	bucketEditModal.find('form').before($.dfaceAlert('danger', '<strong>Error: </strong>' + result.message));
	            }
	        })
	    });
	});

	function onBucketSelectFn(_this) {
		bucketSelectDiv.find('button').html(_this.text() + ' <span class="caret">');
        dataStorage.buckets.current = getCurrentBucket(_this.parent().data('sid'));
        searchInput.val('');
        loadResourceListOfCurrentBucket();
        disableView(false);
	}

	function disableView(disabled) {
		bucketEditBtn.prop('disabled', disabled);
		uploadBtn.prop('disabled', disabled);
		searchBtn.prop('disabled', disabled);
		disabled ? paginationDiv.parent().hide() : paginationDiv.parent().show();
	}

	function constructBucketForm(bucket) {
		return '<form action="">' +
	                '<div class="form-group">' +
	                    '<label for="">空间名称</label>' +
	                    '<input class="form-control" type="text" value="' + (bucket.name || '') + '">' +
	                '</div>' + 
	                '<div class="form-group">' +
	                    '<label for="">空间地址</label>' +
	                    '<input class="form-control" type="text" value="' + (bucket.url || '') + '">' +
	                '</div>' +
	                '<div class="form-group">' +
	                    '<label for="">空间描述</label>' +
	                    '<input class="form-control" type="text" value="' + (bucket.desc || '') + '">' +
	                '</div>' +
	            '</form>';
	}

	function getCurrentBucket(id) {
		return dataStorage.buckets.all.filter(function(bucket) {
			return bucket.sid == id;
		})[0];
	}

	function getFormatedSize(originalSize) {
		var retSize = originalSize;
		var i = 0;
		while (retSize > 900) {
			retSize /= 1024;
			i++;
		}
		return Math.round(retSize * 100) / 100 + fileSizeExt[i];
	}

	function loadResourceListOfCurrentBucket() {
		$.get(URLS['STORAGE_BUCKET_BY_ID_RESOURCE_PAGE_LIST_URL'](dataStorage.buckets.current.sid), {
			descKey: searchInput.val() || undefined,
			pageNo: 1,
			pageSize: GLOBAL_CONSTANT.PAGE_SIZE
		}, function(pageModel) {
			console.log(pageModel)
			resourceListDiv.empty();
			$.each(pageModel.objects, function(i, resource) {
				resourceListDiv.append(constructResourceDom(resource));
			});
			dataStorage.page.totalPages = pageModel.totalPageNo || 1;
			dataStorage.page.currentPage = 1;
			if (dataStorage.page.pagination) {
				dataStorage.page.pagination.data('twbs-pagination').destroy();
			}
			dataStorage.page.pagination = paginationDiv.twbsPagination({
		        totalPages: dataStorage.page.totalPages,
		        visiblePages: 5,
		        initiateStartPageClick: false,
		        onPageClick: function(event, page) {
		        	dataStorage.page.currentPage = page;
		            $.get(URLS['STORAGE_BUCKET_BY_ID_RESOURCE_PAGE_LIST_URL'](dataStorage.buckets.current.sid), {
		            	descKey: searchInput.val() || undefined,
		                pageNo: page,
		                pageSize: GLOBAL_CONSTANT.PAGE_SIZE
		            }, function(result) {
		                resourceListDiv.empty();
	                    $.each(result.objects, function(index, value) {
	                        resourceListDiv.append(constructResourceDom(value));
	                    });
		            });
		        }
		    });
		});
	}

	uploadBtn.on('click', function() {
		var uploadModal = $.dfaceModal({
				title: '文件上传',
				content: constructUploadForm(),
	            isForm: true,
	            backdrop: 'static',
	            keyboard: false,
	            notDismiss: true,
				btns: ['取消', '确定']
			}).show();
		var formDiv = uploadModal.find('form'),
			progressDiv = constructProgress('上传中...');
		uploadModal.find('.modal-body').before(progressDiv);
		uploadModal.find('.close').on('click', function() {
			if (progressDiv.css('display') != 'none') {
				 $.dfaceModal({
		            title: '提示',
		            content: '文件正在上传, 请等待',
		            sizeClass: 'modal-sm',
		            btns: ['确定']
		        }).show();
			} else {
				uploadModal.modal('hide');
			}
		});
		uploadModal.find('#btnOk').on('click', function() {
			progressDiv.show();
			var file = formDiv.find('input[type="file"]')[0].files[0],
				formData = new FormData();
			formData.append('file', file);
			formData.append('description', formDiv.find('textarea').val());
			$.ajax({
				url: URLS['STORAGE_BUCKET_BY_ID_RESOURCE_ACTION_UPLOAD_URL'](dataStorage.buckets.current.sid),
				data: formData,
				type: 'POST',
				cache: false,
				contentType: false,
				processData: false
			}).done(function(result) {
				progressDiv.hide();
		        if (result.succeeded) {
		        	searchInput.val('');
		        	loadResourceListOfCurrentBucket();
		        	uploadModal.modal('hide');
		        } else {
		        	formDiv.before($.dfaceAlert('danger', '<strong>Error: </strong>' + result.message));
		        }
			});
		});
		// $('#uploadModal').modal('show');
	});

	searchBtn.on('click', function(e) {
		e.preventDefault();
		loadResourceListOfCurrentBucket();
	})

	$('#refreshBtn').on('click', function() {
		searchInput.val('');
		loadResourceListOfCurrentBucket();
	});

	function constructUploadForm() {
		return '<form action="">' +
                    '<div class="form-group">' +
                        '<label for="">文件选择</label>' +
                        '<div class="input-group">' +
                            '<input class="form-control" style="cursor: default;" type="text" disabled="true">' +
                            '<span class="input-group-btn">' +
                                '<button class="btn btn-success" style="position: relative; overflow: hidden;">' +
                                    '<span class="glyphicon glyphicon-folder-open"></span>' +
                                    '<input type="file" accept="image/*, audio/*, video/*"' +
                                    	'style="position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; opacity: 0; cursor: inherit;">' +
                                '</button>' +
                            '</span>' +
                        '</div>' +
                    '</div>' +
                    '<div class="form-group">' +
                        '<label for="">文件描述</label>' +
                        '<textarea class="form-control" row="5"></textarea>' +
                    '</div>' +
                '</form>';
	}

	function constructProgress(msg) {
		return $('<div class="progress" style="margin-bottom: 0px; border-radius: 0px; display: none;">' +
	              '<div class="progress-bar progress-bar-info progress-bar-striped active" style="width: 100%;">' + 
	              		msg + '</div>' +
	            '</div>');
	}

	function constructDelModalContent(resourceList) {
		var retContent = '';
		for(var i = 0; i < resourceList.length; i++) {
			retContent += '<div class="alert alert-info" style="margin-bottom: 10px;" data-sid="' + 
								resourceList[i].data('sid') + '">' + resourceList[i].find('td:eq(1)').text() +
			                // '<button class="close" data-toggle="tooltip" data-placement="left" title="fdsfsfd">Error!</button>' +
			              '</div>';
		}
		return retContent;
	}

	function constructResourceDom(resource) {
		return '<tr data-sid="' + resource.sid + '">' +
                    '<td>' + resource.name + '</td>' +
                    '<td>' + resource.description + '</td>' +
                    '<td>' + 
	                    '<div class="input-group input-group-sm" style="margin-right: 20px;">' + 
	                        '<input type="text" class="form-control" readonly ' +
	                        	'value="' + dataStorage.buckets.current.url + resource.key + '" onclick="this.select();">' +
	                        '<span class="input-group-btn">' +
	                            '<a class="btn btn-info" target="_blank" href="' + dataStorage.buckets.current.url + resource.key + '" >浏览</a>' + 
	                        '</span>' + 
	                    '</div>' +
	                '</td>' +
                    '<td>' + resource.mimeType + '</td>' +
                    '<td>' + resource.createAt + '</td>' +
                    '<td>' + getFormatedSize(resource.size) + '</td>' +
                    '<td>' + resource.user.name + '</td>' +
                '</tr>';
	}



});